﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Configuration;


/// <summary>
/// Summary description for MyWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService {

    public MyWebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string CreateUser(string Name, string Surname, string Username, string password, string PicturePath)
    {

        ServiceReference2.BankaSoapClient banka = new ServiceReference2.BankaSoapClient();
        String conn = ConfigurationManager.ConnectionStrings["konekcija"].ConnectionString;
        OleDbConnection DBCon = new OleDbConnection(conn);

        try
        {

            DBCon.Open();
            string sql1 = "Select count(*) as NoUsers from [user] where KorisnickoIme = ?";
            OleDbCommand Com1 = new OleDbCommand(sql1, DBCon);
            
            OleDbParameter usernamePrm = new OleDbParameter("@KorisnickoIme", OleDbType.VarChar);
            usernamePrm.Value = Username;
            Com1.Parameters.Add(usernamePrm);

           
            OleDbDataReader dr = Com1.ExecuteReader();

            int numberOfUsers=0;
         

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    int ordMax = dr.GetOrdinal("NoUsers");

                    numberOfUsers = Int32.Parse(dr.GetValue(ordMax).ToString());
                   
                }

            }

            if (numberOfUsers == 0)
            {

                string sql = "INSERT INTO [user]( Ime, Prezime, KorisnickoIme, Lozinka, SlikaPateka) VALUES(?, ?, ?, ?, ?) ";
                OleDbCommand Com = new OleDbCommand(sql, DBCon);
                Com.Parameters.AddWithValue("?", Name);
                Com.Parameters.AddWithValue("?", Surname);
                Com.Parameters.AddWithValue("?", Username);
                Com.Parameters.AddWithValue("?", password);
                Com.Parameters.AddWithValue("?", PicturePath);

              
                Com.ExecuteNonQuery();

                banka.depositMoney(Username, 100);
                

             
                return "OK";
            }
            else
            {
                return "Веќе постои регистриран корисник со тоа корисничко име. Ве молиме изберете друго корисничко име!";
            }

        }
        catch (OleDbException ex)
        {
            string errorMessages = "";

            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages += "Index #" + i + "\n" +
                                 "Message: " + ex.Errors[i].Message + "\n" +
                                 "NativeError: " + ex.Errors[i].NativeError + "\n" +
                                 "Source: " + ex.Errors[i].Source + "\n" +
                                 "SQLState: " + ex.Errors[i].SQLState + "\n";
            }
            return errorMessages;
        }
        finally
        {
            DBCon.Close();
            DBCon.Dispose();

        }


    }

    [WebMethod]
    public User loginUser(string username_in, string password_in)
    {

        String conn = ConfigurationManager.ConnectionStrings["konekcija"].ConnectionString;
        OleDbConnection DBCon = new OleDbConnection(conn);

        try
        {

            DBCon.Open();
            string query = "SELECT user.ID, user.Ime, user.Prezime, user.KorisnickoIme, user.Lozinka, user.SlikaPateka FROM [user] "
                    + " WHERE user.KorisnickoIme = ? and user.Lozinka = ?";


            OleDbCommand comm = new OleDbCommand(query, DBCon);
       

            OleDbParameter usernamePrm = new OleDbParameter("@KorisnickoIme", OleDbType.VarChar);
            usernamePrm.Value = username_in;
            comm.Parameters.Add(usernamePrm);

            OleDbParameter passwordPrm = new OleDbParameter("@Lozinka", OleDbType.VarChar);
            passwordPrm.Value = password_in;
            comm.Parameters.Add(passwordPrm);
        
            OleDbDataReader dr = comm.ExecuteReader();

            string username = "";
            string name1 = "";
            string name2= "";
            string picture = "";
            string errorMessage;

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    int ordUsername = dr.GetOrdinal("KorisnickoIme");
                    int ordName = dr.GetOrdinal("Ime");
                    int ordSurname = dr.GetOrdinal("Prezime");
                    int ordPicture = dr.GetOrdinal("SlikaPateka");

                    username = dr.GetValue(ordUsername).ToString();
                    name1 = dr.GetValue(ordName).ToString();
                    name2 = dr.GetValue(ordSurname).ToString();
                    picture = dr.GetValue(ordPicture).ToString();

                }
                errorMessage = "Успешно се логиравте";  

            }
            else
            {
                errorMessage = "Не е најден корисник со такво корисничко име и лозинка!";
            }

            return new User
            {
                FirstName = name1,
                LastName = name2,
                Username = username,
                Password = "",
                PicturePath = picture,
                errorMessage = errorMessage
            };

            
        }
        catch (OleDbException ex)
        {
            string errorMessages = "";

            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages += "Index #" + i + "\n" +
                                 "Message: " + ex.Errors[i].Message + "\n" +
                                 "NativeError: " + ex.Errors[i].NativeError + "\n" +
                                 "Source: " + ex.Errors[i].Source + "\n" +
                                 "SQLState: " + ex.Errors[i].SQLState + "\n";
            }
            return new User
            {
                FirstName = "",
                LastName = "",
                Username = "",
                Password = "",
                PicturePath = "",
                errorMessage = errorMessages
            };
        }
        finally
        {
            DBCon.Close();
            DBCon.Dispose();

        }
    }
}

